package org.zhxy.core.upload;

import com.baidu.aip.util.Base64Util;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.zhxy.common.aop.AutomaticLog;
import org.zhxy.common.config.MapperFactory;
import org.zhxy.common.config.ServerFactory;
import org.zhxy.common.error.CommonException;
import org.zhxy.common.response.Result;
import org.zhxy.common.response.ResultCode;
import org.zhxy.common.utils.BaiduAiUtil;
import org.zhxy.common.utils.Constants;
import org.zhxy.common.utils.IdWorker;
import org.zhxy.common.utils.UploadUtils;
import org.zhxy.entity.system.User;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/image")
public class UploadTeacherPictureController {


    @AutomaticLog("上传图片到FastDFS")
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Result uploadImagesToServer(@RequestParam("file") MultipartFile file, @RequestParam("id")String id) throws IOException, CommonException {
       String url = "";
        Map<String, Object> map = new HashMap<>();
        String imgBase64 =  Base64Util.encode(file.getBytes());
        if(id == null || "".equals(id)){
            String userId = new IdWorker().nextId();
            String msg = ServerFactory.baiduAiUtil.faceRegister(userId, imgBase64);
            if(!msg.equals("")) throw new CommonException(ResultCode.UPLOAD_ERROR);
            String uploadFile = UploadUtils.createUploadFile(ServerFactory.fastFileStorageClient, file);
            url = Constants.SERVER.FAST_DFS_SERVER_URL + uploadFile;
            map.put(Constants.DB.ID,userId);
        }else if(id != null && !"".equals(id)){
            String msg = ServerFactory.baiduAiUtil.faceUpdate(id, imgBase64);
            if(!msg.equals("")) throw new CommonException(ResultCode.UPLOAD_ERROR);
            String uploadFile = UploadUtils.createUploadFile(ServerFactory.fastFileStorageClient, file);
            url = Constants.SERVER.FAST_DFS_SERVER_URL + uploadFile;
            User user = MapperFactory.userMapper.selectById(id);
            user.setUrl(url);
            MapperFactory.userMapper.updateById(user);
            map.put(Constants.DB.ID,id);
        }
        map.put(Constants.DB.URL,url);
        return new Result(ResultCode.SUCCESS_NO_MESSAGE,map);
    }
}
